package com.wzh.mysending.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.wzh.mysending.R;
import com.wzh.mysending.adapter.LocListAdapter;
import com.wzh.mysending.base.BaseActivity;
import com.wzh.mysending.config.Constant;
import com.wzh.mysending.model.LocationEntity;
import com.wzh.mysending.model.UserEntity;
import com.wzh.mysending.utils.loc.LocationUtil;
import com.wzh.mysending.utils.loc.OnGetLocationChanged;
import com.wzutils.TimeUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

public class LocMapActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener, OnGetLocationChanged, SwipeRefreshLayout.OnRefreshListener{

    @BindView(R.id.map)
    MapView mapView;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    private AMap aMap;
    Intent intent;
    Bundle bundle;
    UserEntity userEntity;
    @BindView(R.id.my_rec)
    RecyclerView myRec;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    LocListAdapter locListAdapter;
    private int limit = 10;        // 每页的数据是10条
    private int curPage = 0;        // 当前页的编号，从0开始
    LocationUtil locationUtil;
    double lat, lot;
    private MarkerOptions markerOption;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loc_map);
        ButterKnife.bind(this);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        initView();
        initEnent();
    }



    private void initView() {
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        intent = getIntent();
        bundle = intent.getExtras();
        userEntity = (UserEntity) bundle.getSerializable(Constant.USER_ENTITY);
        lat = bundle.getDouble(Constant.LAT);
        lot = bundle.getDouble(Constant.LOT);
        setTitleBar(toolbar, userEntity.getUserName());
        setRefresh(mySwf);
        setRecy(myRec);
        initAdapter();
        String updateTime = userEntity.getUpdatedAt();
        long uptime = TimeUtils.stringTolong(updateTime, TimeUtils.YEAR_MONTH_DAY_HOUR_MIN_SS);
        long sytime = TimeUtils.systemTimeLong();
        locationUtil = new LocationUtil(context, this);
        if (Math.abs(uptime - sytime) >= (5 * 60 * 1000)) {
            locationUtil.startLocation();
            Log.e("gengxin", "时间太长了需要更新");
        } else {
            if (lat != 0 && lot != 0) {
                locListAdapter.setLatAndLot(lat, lot);
                addData();
            } else {
                locationUtil.startLocation();
            }

            Log.e("buyonggengxin", "不需要更新");
        }
    }

    private void addMarkersToMap(LatLng latLng) {
        markerOption = new MarkerOptions().icon(BitmapDescriptorFactory
                .defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                .position(latLng)
                .draggable(true);
        aMap.addMarker(markerOption);
    }

    private void initEnent() {
        mySwf.setOnRefreshListener(this);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        myRec.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                LocationEntity locationEntity = (LocationEntity) adapter.getItem(position);
                if (TextUtils.isEmpty(locationEntity.getAddRess())) {
                    changeLocation(locationEntity);
                }
            }
        });
    }

    private void changeLocation(LocationEntity locationInfo) {
        GeocodeSearch geocoderSearch = new GeocodeSearch(getBaseContext());//传入context
        LatLonPoint latLonPoint = new LatLonPoint(locationInfo.getLat(), locationInfo.getLot());
        // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 100, GeocodeSearch.AMAP);
        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                if (i == 1000) {
                    if (regeocodeResult != null && regeocodeResult.getRegeocodeAddress() != null
                            && regeocodeResult.getRegeocodeAddress().getFormatAddress() !=
                            null) {
                        Toast.makeText(getBaseContext(), regeocodeResult.getRegeocodeAddress().getFormatAddress() +
                                "附近", Toast.LENGTH_LONG).show();
                    }

                } else {
                    Toast.makeText(getBaseContext(), "位置太偏暂时查询不到道路信息。", Toast.LENGTH_LONG).show();

                }
            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

            }
        });
        geocoderSearch.getFromLocationAsyn(query);
    }

    private void addData() {
        if (locationUtil != null) {
            locationUtil.stopLocation();
        }

        BmobQuery<LocationEntity> bmobQuery = new BmobQuery<>();
        bmobQuery.order("-updatedAt");
        bmobQuery.setLimit(limit);
        if (curPage != 0) {
            bmobQuery.setSkip(curPage * limit);
        } else {
            bmobQuery.setSkip(curPage);
        }
        bmobQuery.addWhereEqualTo("userId", userEntity.getObjectId());
        bmobQuery.findObjects(new FindListener<LocationEntity>() {
            @Override
            public void done(List<LocationEntity> list, BmobException e) {
                mySwf.setRefreshing(false);
                if (e == null) {
                    Log.e("查询成功：共", list.size() + "条数据。");
                    Log.e("查询成功：", list.toString());

                    if (list.size()!=0){
                        if (curPage == 0) {
                            LatLng marker = new LatLng(list.get(0).getLat(), list.get(0).getLot());
                            //设置中心点和缩放比例

                            aMap.moveCamera(CameraUpdateFactory.changeLatLng(marker));
                            aMap.moveCamera(CameraUpdateFactory.zoomTo(12));

                            addMarkersToMap(marker);
                            locListAdapter.setNewData(list);
                        } else {
                            locListAdapter.addData(list);
                        }
                    }

                    if (list.size() != 10) {
                        locListAdapter.loadMoreEnd(false);
                    } else {
                        locListAdapter.loadMoreComplete();
                        curPage++;
                    }
                } else {
                    toast("查询失败");
                }
            }
        });
    }

    private void initAdapter() {
        locListAdapter = new LocListAdapter(R.layout.item_loc, new ArrayList<LocationEntity>());
        locListAdapter.setEmptyView(emptyView);
        locListAdapter.setOnLoadMoreListener(this, myRec);
        locListAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_LEFT);
        myRec.setAdapter(locListAdapter);
    }

    @Override
    public void onLoadMoreRequested() {
        addData();
    }

    @Override
    public void onLocationOk(AMapLocation aMapLocation) {
        Log.e("OK==", aMapLocation.toString());
        lat = aMapLocation.getLatitude();
        lot = aMapLocation.getLongitude();
        locListAdapter.setLatAndLot(lat, lot);
        addData();
    }

    @Override
    public void onLocationError(AMapLocation aMapLocation) {
        Log.e("onLocationError==", aMapLocation.toString());
        toast("获取定位信息失败，距离显示不准确");
        lat = 0;
        lot = 0;
        locListAdapter.setLatAndLot(lat, lot);
        addData();
    }

    @Override
    public void onLocationNull(AMapLocation aMapLocation) {
        toast("获取定位信息失败，距离显示不准确");
        Log.e("onLocationNull==", aMapLocation.toString());
        lat = 0;
        lot = 0;
        locListAdapter.setLatAndLot(lat, lot);
        addData();
    }

    @Override
    public void onRefresh() {
        limit = 10;        // 每页的数据是10条
        curPage = 0;        // 当前页的编号，从0开始
        if (locationUtil != null) {
            locationUtil.startLocation();
        } else {
            locationUtil = new LocationUtil(getApplicationContext(), this);
            locationUtil.startLocation();
        }
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }


}
